package com.aiyan.edu.service.auth.center.userdetails;

import com.aiyan.edu.framework.domain.ucenter.Menu;
import com.aiyan.edu.framework.domain.ucenter.ext.UserExt;
import com.aiyan.edu.framework.model.response.CommonResponseResult;
import com.aiyan.edu.service.auth.center.client.UserClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: zqzhou
 * @create: 2019/11/21 16:42
 **/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("1234"));
    }

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (null == authentication) {
            //先统一采用httpbasic认证校验一次客户端信息，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if (null != clientDetails) {
                String clientSecret = clientDetails.getClientSecret();
                return new User(username, clientSecret, AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }

        if (StringUtils.isEmpty(username)) {
            return null;
        }
        //远程调用用户中心根据账号查询用户信息
        CommonResponseResult<UserExt> responseResult = this.userClient.getUserExt(username);
        if (!responseResult.isSuccess() || responseResult.getResult() == null) {
            return null;
        }
        UserExt userext = responseResult.getResult();

        //取出正确密码（hash值）
        String password = userext.getPassword();
        //从数据库获取权限
        List<Menu> permissions = userext.getPermissions();
        if (permissions == null) {
            permissions = new ArrayList<>();
        }
        List<String> user_permission = new ArrayList<>();
        permissions.forEach(item -> user_permission.add(item.getCode()));

        String user_permission_string = StringUtils.join(user_permission.toArray(), ",");
        UserJwt userDetails = new UserJwt(username,
                password,
                AuthorityUtils.commaSeparatedStringToAuthorityList(user_permission_string));
        userDetails.setId(userext.getId());
        userDetails.setUtype(userext.getUtype());
        userDetails.setCompanyId(userext.getCompanyId());
        userDetails.setName(userext.getName());
        userDetails.setUserpic(userext.getUserpic());

        return userDetails;
    }
}
